package com.miaoda.miaoda_ai.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.miaoda.miaoda_ai.ai.model.HtmlCodeResult;
import com.miaoda.miaoda_ai.ai.model.MultiFileCodeResult;
import com.miaoda.miaoda_ai.constant.AppConstant;

import java.io.File;


public class CodeFileSaver {

    /**
     * 文件保存根路径
     */
    private static final String FILE_SAVE_ROOT_DIR = AppConstant.CODE_OUTPUT_ROOT_DIR;

    // 保存单个文件
    public static void saveFile(String dirPath, String fileName, String content) {
        String filePath = dirPath + File.separator + fileName;
        FileUtil.writeString(content, filePath, "UTF-8");
    }

    /**
     * 构建唯一文件路径
     *
     * @param bizType
     * @return
     */
    public static String buildUniqueFilePath(String bizType) {
        // 生成唯一文件名,使用雪花算法
        String uniqueFileName = StrUtil.format("{}_{}", bizType, IdUtil.getSnowflakeNextIdStr());
        String dirPath = FILE_SAVE_ROOT_DIR + File.separator + uniqueFileName;
        FileUtil.mkdir(dirPath);
        return dirPath;

    }

    /**
     * 保存html代码
     *
     * @param htmlCodeResult
     * @return
     */
    public static File saveHtmlCode(HtmlCodeResult htmlCodeResult) {
        String dirPath = buildUniqueFilePath("html");
        saveFile(dirPath, "index.html", htmlCodeResult.getHtmlCode());
        return new File(dirPath);
    }

    /**
     * 保存多文件代码
     *
     * @param multiFileCodeResult
     * @return
     */
    public static File saveMultiFileCode(MultiFileCodeResult multiFileCodeResult) {
        String dirPath = buildUniqueFilePath("multi_file");
        saveFile(dirPath, "index.html", multiFileCodeResult.getHtmlCode());
        saveFile(dirPath, "style.css", multiFileCodeResult.getCssCode());
        saveFile(dirPath, "script.js", multiFileCodeResult.getJsCode());
        return new File(dirPath);
    }
}
